import { cloneDeep } from "lodash-es";
import React, { useContext, useReducer } from "react";

import { GlobalContainerProps, UserInfo } from "./index.d";
export type { ContentType as GlobalContentType } from "./index.d";

/****************************** createContext ******************************/

// 全局对象,先定义后使用
export const globalInit = {
  reset: "",
  /** 右侧导航栏是否收缩 */
  sideMenuCollapse: false,
  userInfoData: {} as UserInfo,
  MENU_LIST: null as null | any[],
  /** 系统信息 */
  systemInfo: {} as any,
  signalRConnection: null as any,
  powerButtonList: null as null | string[], // 用户所有有权限的按钮的标识列表
  /** 菜单选中数据 */
  sideMenuSelectData: {} as any | {},
};

export const GlobalContext = React.createContext({} as any);
// 全局容器
export const GlobalContainer = (props: GlobalContainerProps) => {
  const reducer = (prevState: any, act: any) => {
    let newState = { ...prevState };
    const { type, data } = act;
    if (!type) {
      new Error("not type");
    }
    if (type in globalInit) {
      newState[type] = data;
    }
    // 重置store
    if (type == "reset") {
      newState = cloneDeep({
        ...globalInit,
        // systemInfo 不重置 避免退出登录后拿不到系统信息
        systemInfo: newState.systemInfo,
      });
    }
    return newState;
  };

  const [global, globalDispatch] = useReducer(reducer, cloneDeep(globalInit));

  return (
    <GlobalContext.Provider
      value={{
        global,
        globalDispatch,
      }}
    >
      {props.children}
    </GlobalContext.Provider>
  );
};

export default GlobalContainer;

type globalInitType = typeof globalInit;

/** useContent 类型 */
export interface ContentType {
  global: globalInitType;
  globalDispatch: <T extends keyof globalInitType>(newDate: { type: T; data: globalInitType[T] }) => any;
}
/**
 * 使用 global 数据的 快捷封装
 */
export const useGlobalContent = () => {
  const { global, globalDispatch } = useContext<ContentType>(GlobalContext);
  return { global, globalDispatch };
};
